//
//  XMGScheduleViewController.m
//  码哥课堂
//
//  Created by yz on 2016/11/23.
//  Copyright © 2016年 yz. All rights reserved.
//

#import "XMGScheduleViewController.h"
#import "AFHTTPSessionManager+XMGManager.h"
#import "XMGNetworkManager.h"
#import <MJExtension.h>
#import "XMGMonthItem.h"
#import "XMGDayItem.h"
#import "XMGScheduleCell.h"
#import "XMGScheduleView.h"
#import "UIColor+Color.h"
#import <SVProgressHUD.h>

static NSString *const ID = @"schedule";
@interface XMGScheduleViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) XMGScheduleView *scheduleView;
@property (nonatomic, strong) NSMutableArray *months;
@property (nonatomic, strong) XMGMonthItem *curMonth;
@property (nonatomic, assign) NSInteger curWeek;
@property (nonatomic, assign) NSInteger lastMonth;
@property (nonatomic, strong) NSArray *weekDays;
@property (nonatomic, weak) UIRefreshControl *refreshControl;
@property (nonatomic, strong) UIView *weekBackgroundColorView;
@end

@implementation XMGScheduleViewController
- (UIView *)weekBackgroundColorView
{
    if (_weekBackgroundColorView == nil) {
        _weekBackgroundColorView = [[UIView alloc] init];
        _weekBackgroundColorView.backgroundColor = [UIColor colorWithHexString:@"#198fee"];
    }
    return _weekBackgroundColorView;
}
- (NSMutableArray *)months
{
    
    if (_months == nil) {
        _months = [NSMutableArray array];
    }
    return _months;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    XMGScheduleView *scheduleView = [XMGScheduleView scheduleView];
    [self.view addSubview:scheduleView];
    _scheduleView = scheduleView;
    
    _scheduleView.frame = [UIScreen mainScreen].bounds;
    UICollectionViewFlowLayout *layout = _scheduleView.collectionView.collectionViewLayout;
    
    layout.itemSize = CGSizeMake(XMGScreenWidth - 100, (XMGScreenHeight - 64 - 49 - 40 - 42));
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    [self loadSchedule];
    
    // 设置colletionView
    [self setupColletionView];
    
    // 添加下拉刷新
    [self setupRefreshView];
    
    _scheduleView.block = ^(){
        // 多记录 少遍历
        // 获取当前周在哪个月（搞个属性记录下）
        NSInteger month = [self.months indexOfObject:_curMonth];
        
        // 获取当前周属于第几个月
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:_curWeek inSection:month];
        
        [self.scheduleView.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        
    };
    
    _weekDays = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    
    _lastMonth = -1;
}

// 添加下拉刷新
- (void)setupRefreshView
{
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    _refreshControl = refreshControl;
    [refreshControl addTarget:self action:@selector(reloadLastMonth) forControlEvents:UIControlEventValueChanged];
    _scheduleView.collectionView.refreshControl = refreshControl;
}

- (void)reloadLastMonth
{
    // 获取课表参数
    NSDictionary *param = [XMGNetworkManager paramWithScheduleWithNextMonthIndex:_lastMonth];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    AFJSONResponseSerializer *jsonRep = [AFJSONResponseSerializer serializer];
    jsonRep.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    mgr.responseSerializer = jsonRep;
    
    [mgr POST:@"https://www.yunke.com/interface/plan/tablev2" parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        
        
        // 结束下拉刷新
        [_refreshControl endRefreshing];
        
        _lastMonth--;
        
        // 月模型
        XMGMonthItem *month = [XMGMonthItem mj_objectWithKeyValues:responseObject[@"result"]];
        
        [self.months insertObject:month atIndex:0];
        
        [_scheduleView.collectionView reloadData];
        
        // 滚动到上一页
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:4 inSection:0];
        [self.scheduleView.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

- (void)setupColletionView
{
    _scheduleView.collectionView.pagingEnabled = YES;
    _scheduleView.collectionView.showsVerticalScrollIndicator = NO;
    _scheduleView.collectionView.delegate = self;
    _scheduleView.collectionView.dataSource = self;
    _scheduleView.collectionView.backgroundColor = COLOR(246, 246, 246, 1);
    
    // 注册cell
    [_scheduleView.collectionView registerClass:[XMGScheduleCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.months.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    XMGMonthItem *month = self.months[section];
    return month.data.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XMGScheduleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    XMGMonthItem *monthItem = self.months[indexPath.section];
    
    // 获取一周的数据
    cell.days = monthItem.data[indexPath.row];
    
    return cell;
}


- (void)loadSchedule
{
//    AFHTTPSessionManager *mgr = [AFHTTPSessionManager xmg_manager];
    
    // 获取课表参数
    NSDictionary *param = [XMGNetworkManager paramWithScheduleWithNextMonthIndex:0];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    AFJSONResponseSerializer *jsonRep = [AFJSONResponseSerializer serializer];
    jsonRep.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    mgr.responseSerializer = jsonRep;
    
    [mgr POST:@"https://www.yunke.com/interface/plan/tablev2" parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
        
        // 月模型
        XMGMonthItem *month = [XMGMonthItem mj_objectWithKeyValues:responseObject[@"result"]];
        [self.months addObject:month];
        
        // 第一次获取的月份 就是当前月份 记录下
        _curMonth = month;
        
        // 获取当前周是第几个月
        _curWeek = [self curWeekInMonth];
        
        [_scheduleView.collectionView reloadData];
      
        // 滚动到当前周
        [self scrollCurWeek];
        
        // 设置左边的View
        [self setupLeftWeekView];
        
//        NSLog(@"%@",responseObject);
//        [responseObject writeToFile:@"/Users/yuanzheng/Documents/码哥课堂1/schedule.plist" atomically:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

- (NSInteger)curWeekInMonth{
    int i = 0;
    
    for (NSArray *week in _curMonth.data) {
        
        for (XMGDayItem *day in week) {
            // 判断是否属于当前周
            if ([day.date isEqualToString:_curMonth.today]) {
                return i;
            }
        }
        
        
        i++;
    }
    
    return -1;
}

- (void)scrollCurWeek
{
    // 多记录 少遍历
    // 获取当前周在哪个月（搞个属性记录下）
    NSInteger month = [self.months indexOfObject:_curMonth];
    
    // 获取当前周属于第几个月
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:_curWeek inSection:month];
    
    [self.scheduleView.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}

- (void)setupLeftWeekView
{
    // 一月对应cell 可以根据scrollView的偏移量判断当前月份
    
    
    // 获取月份
    CGFloat offsetY = _scheduleView.collectionView.contentOffset.y;
    CGFloat collectionH = (XMGScreenHeight - 64 - 49 - 40 - 42);
    
    // 获取哪一个月
    NSInteger month = offsetY / (collectionH * 5);
    
    // 获取哪一周
    NSInteger week = (int)(offsetY / collectionH) % 5;
    
    XMGMonthItem *monthItem = self.months[month];
    NSArray *days = monthItem.data[week];
    
//    NSLog(@"第%d月 第%d周",month,week);
    
    NSInteger day = 0;
    // 一个cell显示一周
    for (UILabel *label in _scheduleView.weekLabels) {
        
        XMGDayItem *dayItem = days[day];
        label.text = dayItem.dateStr;
        
        
        // 判断是否显示今天
        if ([dayItem.date isEqualToString:_curMonth.today]) {
            // 获取父控件
            UIView *superView = label.superview;
            UILabel *label = superView.subviews[0];
            label.text = @"今天";
            
            self.weekBackgroundColorView.frame = CGRectMake(0, 0, 70, 70);
            self.weekBackgroundColorView.center = CGPointMake(superView.width * 0.5, superView.height * 0.5);
            self.weekBackgroundColorView.layer.cornerRadius = self.weekBackgroundColorView.height / 2.0;
            
            [superView insertSubview:self.weekBackgroundColorView atIndex:0];
            
            
            
        } else {
            // 还原日期
            UIView *superView = label.superview;
            UILabel *label = superView.subviews[0];
            
            if ([label isMemberOfClass:[UIView class]]) {
                [label removeFromSuperview];
            } else {
                
                label.text = _weekDays[day];
            }
            
    
        }
        day++;
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 更新右边视图显示
    [self setupLeftWeekView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    // 没有更新内容 不需要显示
    if (scrollView.contentSize.height < (scrollView.height * self.months.count * 5) || scrollView.contentSize.height == 0) {
        return;
    }
    
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY >= scrollView.contentSize.height - scrollView.height) {
        
        // 自定义样式
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
        
        // 蒙版样式
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        
        // 框框背景色
        [SVProgressHUD setBackgroundColor:[UIColor blackColor]];
        // 字体颜色
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        
        [SVProgressHUD showImage:nil status:@"没有更多的课程"];

    }
}

@end
